﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Windows;

namespace HB.MVVM
{
#if NET40 || NET45
    /// <summary>
    /// 可通知集合类型（拓展）
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class ObservableCollectionEx<T> : ObservableCollection<T>
    {
        /// <summary>
        /// 通知单个元素
        /// </summary>
        /// <param name="index"></param>
        public void NotifyItemChanged(int index)
        {
            lock (this)
            {
                var pair = this[index];
                this.OnCollectionChangedAction(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, pair, index));
                this.OnCollectionChangedAction(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, pair, index));
            }
        }
        /// <summary>
        /// 强制通知所有元素
        /// </summary>
        public void NotifyAllChanged()
        {
            OnCollectionChangedAction(new System.Collections.Specialized.NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction.Reset));
        }
        /// <summary>
        /// 批量增加
        /// </summary>
        /// <param name="items"></param>
        public void AddRange(params T[] items)
        {
            foreach (var item in items)
            {
                Add(item);
            }
        }
        void OnCollectionChangedAction(NotifyCollectionChangedEventArgs e)
        {
            if (Thread.CurrentThread.ManagedThreadId == Application.Current.Dispatcher.Thread.ManagedThreadId)
            {
                OnCollectionChanged(e);
            }
            else
            {
                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    OnCollectionChanged(e);
                }));
            }
        }
    }
#endif
}
